package com.xy.biz.auth.domain.utils;

import java.util.Random;

/**
 * @author Greekn Zhang
 * @date 2021/10/28 11:10
 * @description 随机密码定长生成
 */
public class PasswordUtils {
    /**
     * 获得密码
     * @param len 密码长度
     * @return 随机密码
     */
    public static String generatePassWord(int len) {
        int random = createRandomInt();
        return createPassWord(random, len);
    }

    private static String createPassWord(int random, int len) {
        Random rd = new Random(random);
        final int maxNum = 66;
        StringBuilder sb = new StringBuilder();
        int rdGet;
        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '@', '&', '>', '<'};
        int count = 0;
        while (count < len) {
            rdGet = Math.abs(rd.nextInt(maxNum));
            if (rdGet >= 0 && rdGet < str.length) {
                sb.append(str[rdGet]);
                count++;
            }
        }
        return sb.toString();
    }

    private static int createRandomInt() {
        final int num = 100000;
        //得到0.0到1.0之间的数字，并扩大100000倍
        double temp = Math.random() * num;
        //如果数据等于100000，则减少1
        if (temp >= num) {
            temp = 99999;
        }
        return (int) Math.ceil(temp);
    }
}
